/**
 * Copyright © 2014 TingerSure. All rights reserved.
 */
package org.sure.scomet.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.sure.scomet.link.Connection;
import org.sure.scomet.link.ConnectionCenter;

public class PageIdManager implements Runnable {
	/**
	 * the page index.
	 */
	private static int pageIndex = 1;

	/**
	 * The page id list what can be use.
	 */
	private static List<Integer> usableID = new LinkedList<Integer>();

	/**
	 * the map of the page id in use and the the corresponding connection
	 */
	private static Map<Integer, Connection> linkMap = new HashMap<Integer, Connection>();

	/**
	 * destroy all attribute in need. It does nothing.
	 */
	public static void destroy() {

	}

	/**
	 * Initialize all attribute in need. It does nothing.
	 */
	public static void init() {

	}

	/**
	 * give a page id to the given connection.
	 * 
	 * @param link
	 *            the given connection
	 * @return the page id
	 */
	public static synchronized int getPageID(Connection link) {
		if (usableID.size() != 0) {
			linkMap.put(usableID.get(0), link);
			return usableID.remove(0);
		}
		linkMap.put(pageIndex, link);
		return pageIndex++;
	}

	/**
	 * Return back a page id.
	 * 
	 * @param id
	 *            the page id
	 */
	public static synchronized void returnPageID(int id) {
		linkMap.remove(id);
		usableID.add(id);
	}

	/**
	 * Get the connection by the page id.
	 * 
	 * @param id
	 *            the page id
	 * @return the connection
	 */
	public static Connection getConnectionByID(int id) {
		return linkMap.get(id);
	}

	/**
	 * the auto check thread.
	 */
	@Override
	public void run() {
		long interval = ConnectionCenter.getMaxWaitTime() < 10 * 60 * 100 ? 10 * 60 * 100
				: ConnectionCenter.getMaxWaitTime();
		while (ConnectionCenter.isAutoCheck()) {
			Iterator<Integer> it = linkMap.keySet().iterator();
			try {
				while (it.hasNext()) {
					ConnectionCenter.check(linkMap.get(it.next()));
				}
				synchronized (this) {
					this.wait(interval);
				}
			} catch (Exception e) {
			}
		}
	}
}
